﻿using Application.Users.Commands.CreateUser;
using Application.Users.Commands.UpdateUser;
using Application.Users.Interfaces;
using Application.Users.Models;
using Domain.Entities;
using Domain.ValueObjects;
using Infrastructure.Data.Contexts;
using Infrastructure.Exceptions;
using Shared.Exceptions;

namespace Infrastructure.Repositories
{
    public class UserWriteRepository(AppDbContext context) : IUserWriteRepository
    {

        public async Task<Guid> AddAsync(User user, CancellationToken ct = default)
        {
            context.Database.EnsureCreated();

            context.Users.Add(user);
            await context.SaveChangesAsync(ct);
            return user.Id;
        }

        public async Task<Guid> UpdateAsync(UpdateUserModel userDTO, CancellationToken ct = default)
        {
            //查出用户实体
            var user = context.Users.Find(userDTO.Id) ?? throw new UserUpdateException("用户不存在");

            //增量更新实现
            if(!string.IsNullOrEmpty(userDTO.UserName))
            {
                user.ChangeUserName(NickName.Create(userDTO.UserName));
            }
            if(!string.IsNullOrEmpty(userDTO.PhoneNumber))
            {
                user.ChangePhoneNumber(PhoneNumber.Create(userDTO.PhoneNumber));
            }
            if(!string.IsNullOrEmpty(userDTO.CollegeName) && !string.IsNullOrEmpty(userDTO.MajorName))
            {
                user.ChangeAcademicInfo(AcademicInfo.Create(userDTO.CollegeName,userDTO.MajorName));
            }

            context.Update(user);
            await context.SaveChangesAsync(ct);
            return user.Id;
        }

        public async Task<bool> DeleteAsync(Guid userId, CancellationToken ct = default)
        {
            var user = context.Users.Find(userId) ?? throw new Exception("User not found");
            
            user.Delete();

            await context.SaveChangesAsync(ct);

            return true;
        }
    }
}
